package src.cs2340.todoApp;

import java.util.ArrayList;
import src.cs2340.todoApp.Date.Meredian;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
/**
 * CreateTaskScreen handles buttonlisteners for create a new task for a user
 * @author Rochelle
 *
 */
public class CreateTaskScreen extends Activity{
	private Spinner spinner;
	ArrayList<Location> locs;
	private AutoCompleteTextView locationView;
	// private account variables
	private String username;
	private String password;
	private String tag;
	private String category;
	private EditText taskName;
	private EditText description;
	private static final int static_int = 10;
	private Location loc;
	private DatePicker datePicker;
	private TimePicker timePicker;
	private Date d;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.createnewtask);

	    // dictates items that exist in the drop down menu
	    spinner = (Spinner) findViewById(R.id.categoryMenu);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.category_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    
	    //TODO: Populate from database unless new user.
	    //TODO: locs = Database.getInstance().getAllLocations(username);
	    locs = LocationList.getLocs();
		ArrayAdapter<Location> locAdapter = new ArrayAdapter<Location>(this,
		android.R.layout.simple_dropdown_item_1line, locs);
		locationView = (AutoCompleteTextView) findViewById(R.id.locationAutoComplete);
		locationView.setAdapter(locAdapter);
		
		// Pickers for date and time
		datePicker = (DatePicker) findViewById(R.id.datePicker);
		timePicker = (TimePicker) findViewById(R.id.timePicker);
		
	    // button access
	    Button create = (Button) findViewById(R.id.createButton);
	    Button cancel = (Button) findViewById(R.id.cancelButton);
	    
	    // parameters passed between various screens
	    Bundle extras = getIntent().getExtras();
	    if (extras != null) {
	    	username = extras.getString("username");
	    	password = extras.getString("password");
	    }
	    
	    // create button's onclick listener
	    create.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// obtain information from the text fields
				taskName = (EditText) findViewById(R.id.taskNamefield);
				description = (EditText) findViewById(R.id.descripField);
				category = spinner.getSelectedItem().toString();
				// check if the new TaskItem at least has a name
				if (taskName.getText() == null || taskName.getText().toString().trim().equals("")) {
					AlertDialog.Builder alertDialog = new AlertDialog.Builder(CreateTaskScreen.this)
						.setTitle("Insufficient info")
						.setMessage("Task name is a required field.")
						.setCancelable(false)
						.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which){
								dialog.cancel();
						}
					});
					AlertDialog alert = alertDialog.create();
					alert.show();
				} else {
					// Handling Date and Time inputs
					int hour = timePicker.getCurrentHour();
					Log.e("hour and AM/PM", "Hour: " + hour);
					d = new Date(datePicker.getDayOfMonth(), (datePicker.getMonth()+1), datePicker.getYear(),
							hour >= 12 ? hour-12 : hour, timePicker.getCurrentMinute(), 
							hour >= 12 ? Meredian.PM : Meredian.AM);
					
					// creates locations for new task items
					loc = null;
					if(!locationView.getText().toString().trim().equals("")){
						// checks to see if location was saved previously
						for(Location l:locs){
							if(locationView.getText().toString().equals(l.toString())){
								loc = l;
								createAndClose(loc, d);
								break;
							}
						}
						if(loc == null){
							// if location is a new location ask if user wants to creat new location
							AlertDialog.Builder alertDialog = new AlertDialog.Builder(CreateTaskScreen.this);
							alertDialog.setTitle("Location Not Found");
							alertDialog.setMessage("Would you like to save this location for future use?");
							alertDialog.setCancelable(false);
							// if user wants to create new location, go to create location screen
							alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which){
									dialog.cancel();
									Intent intent = new Intent(getApplicationContext(), NewLocationScreen.class);
									intent.putExtra("username", username);
									intent.putExtra("password", password);
									intent.putExtra("Tag", locationView.getText().toString().trim());
									startActivityForResult(intent, static_int);
								}
							});
							// if user does not want to create new location continue but location
							//	 will not be a valid address that will show up on the map
							alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									loc = new Location(locationView.getText().toString(),0,null,null,null,0);
									dialog.cancel();
									createAndClose(loc, d);
								}
							});
							AlertDialog alert = alertDialog.create();
							alert.show();
						}
					}
					// if location is left blank, then create an empty location to pass
					else{
						loc = new Location("",0,null,null,null,0);
						createAndClose(loc, d);
					}					
				}
			}
		});
	    
	    // cancel button listener
	    cancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(CreateTaskScreen.this);
				alertDialog.setMessage("Are you sure you want to leave the create new task screen?");
				
				/**
				 * The code called for the "YES" option
				 */
				alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						/**will return user to user task list screen*/
						Intent intent = new Intent(getApplicationContext(), UserTaskListScreen.class);
						intent.putExtra("username", username);
						intent.putExtra("password", password);
						finish();
						startActivity(intent);
					}
				});
				
				/**
				 * The code called for the "NO" option
				 */
				alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				})
				.show();
			}
		});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		switch(requestCode) { 
	    case (static_int) : { 
	      if (resultCode == Activity.RESULT_OK) { 
	      String locText = data.getStringExtra("Tag");
	      locationView.setText(locText);
//	      createAndClose(loc, d);
	      createAndClose(LocationList.getLocs().get(LocationList.getLocs().size()-1), d);
	      } 
	      break; 
	    } 
	  } 
	}
	
	public void createAndClose(Location loc, Date d){
		TaskItem task = new TaskItem(taskName.getText().toString(), loc, d, 
				 description.getText().toString(), category, false);
		// parameters passed between various screens
		Account currAccount = new Account(username, password, null, null, Database.getInstance());
		// get the most updated copy from the db
		currAccount = Database.getInstance().getUpdate(currAccount);
		// add taskitem
		currAccount.addTaskItem(task);
		// update the db
		Database.getInstance().update(currAccount);
		Intent intent = new Intent(getApplicationContext(), UserTaskListScreen.class);
		// add parameters for information sharing
		intent.putExtra("username", username);
		intent.putExtra("password", password);
		finish();
		startActivity(intent);
	}
}
